package com.xwqiang.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xwqiang.handle.AppException;
import com.xwqiang.mapper.SysUserMapper;
import com.xwqiang.pojo.dto.SysUserLoginDto;
import com.xwqiang.pojo.model.AuthorSysUser;
import com.xwqiang.pojo.model.SysUser;
import com.xwqiang.pojo.vo.SysUserLoginVo;
import com.xwqiang.service.SysUserService;
import com.xwqiang.utils.ErrCode;
import com.xwqiang.utils.JwtToken;
import com.xwqiang.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
* @author xwqiang
* @description 针对表【sys_user】的数据库操作Service实现
* @createDate 2024-06-05 23:19:39
*/
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public SysUserLoginVo login(SysUserLoginDto sysUserLoginDto) {
        //调用userDetailsService检测是否有该用户,有则取出用户信息
        AuthorSysUser authorSysUser = (AuthorSysUser) userDetailsService.loadUserByUsername(sysUserLoginDto.getUsername());

        //如果有,则调用原来的认证逻辑
        UsernamePasswordAuthenticationToken authorToken = new UsernamePasswordAuthenticationToken(
                authorSysUser.getUsername(),
                authorSysUser.getPassword(),
                authorSysUser.getAuthorities());

        Authentication authenticate = authenticationManager.authenticate(authorToken);

        //如果认证失败
        if(!authenticate.isAuthenticated()){
            throw new AppException(ErrCode.USER_NAME_PWD_ERROR);
        }


        //构建jwt
        String userId = authorSysUser.getSysUser().getId().toString();
        Map<String,Object> claims = new HashMap<>();
        claims.put("id",userId);
        String jwt = JwtToken.createJWT(claims);
        redisCache.setCacheObject("authorSysUser:"+userId, authorSysUser);

        SysUserLoginVo sysUserLoginVo = new SysUserLoginVo();
        sysUserLoginVo.setUsername(authorSysUser.getUsername());
        sysUserLoginVo.setJwt(jwt);

        return sysUserLoginVo;
    }

}




